package com.hns.tool.task.taque;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 任务提交者
 * 提交待办任务到执行队列
 * @author:wucx
 * @email:zhuangcaijin@126.com
 * @version Revision 2.0.0
 */
public class TaskSubmitter extends Thread{

	private final Logger logger = LoggerFactory.getLogger(TaskSubmitter.class);
	
	/**
	 * 任务执行队列
	 */
	private Taque taque;
	
	Object lock = new Object();
	
	TaskSubmitter(Taque taque) {
		this.taque = taque;
		setDaemon(true);
	}
	
	/**
	 * 执行线程池内任务
	 * @email:zhuangcaijin@126.com
	 */
	public void run() {
		while(taque.isUp) {
			if ( taque.isBusy() ) {
				waiting(10000l);
			} else {
				logger.trace("doings size {}.", taque.doings.size());
				Task task = taque.take();
				if ( task != null ) {
					taque.execute(new TaskRun(task, taque));
				} else {
					waiting(20000l);
				}
			}
		}
	}
	
	/**
	 * 唤醒线程
	 * @author:wucx
	 * @email:zhuangcaijin@126.com
	 */
	public void wakeup() {
		logger.trace("submitter is wakeup.");
		synchronized(lock) {
			lock.notify();
		}
	}
	
	/**
	 * 线程等待
	 * @param time 时间
	 * @author:wucx
	 * @email:zhuangcaijin@126.com
	 */
	public void waiting(long time) {
		try {
			logger.trace("submitter is waiting for {} ms", time);
			synchronized(lock) {
				lock.wait(time);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
